package processor.html;

/**
 * The HtmlProcessor Class.
 *
 * Created: 2-Jan-2012
 * Last Modified: 2-Jan-2012
 * @author Shimu
 */
public class HtmlProcessor {

    public HtmlProcessor() {
    }
    
    // ----------------- HTML TABLE ----------------
    private static final HtmlTag table, tableRow, tableData;

    static {
        table = new HtmlTag("table", "border = \"1\"");
        tableRow = new HtmlTag("tr");
        tableData = new HtmlTag("td");
    }

    /**
     * Surround the given str with an HtmlTag's START_TAG and END_TAG, then
     * append it to the given StringBuilder.
     * 
     * @param str
     * @param builder 
     */
    private void appendWithTag(String str, HtmlTag tag, StringBuilder builder) {
        builder.append(tag.START_TAG);
        builder.append(str);
        builder.append(tag.END_TAG);
    }

    public String toHtmlTable(Object[] array) {
        StringBuilder builder = new StringBuilder(table.LENGTH
                + (tableRow.LENGTH + tableData.LENGTH) * array.length);

        builder.append(table.START_TAG);
        for (Object element : array) {
            builder.append(tableRow.START_TAG);
            tableData.enclose(element, builder);
            builder.append(tableRow.END_TAG);
        }
        builder.append(table.END_TAG);

        return builder.toString();
    }

    public String toHtmlTable(Object[][] array, HtmlAttribute[][] attributes) {
        int rowCount = array.length;
        int columnCount = array[0].length;

        StringBuilder builder = new StringBuilder(table.LENGTH
                + (tableRow.LENGTH + tableData.LENGTH * columnCount)
                * rowCount);

        builder.append(table.START_TAG);

        for (int r = 0; r < rowCount; r++) {
            builder.append(tableRow.START_TAG);
            for (int c = 0; c < columnCount; c++) {
                new HtmlTag("td", attributes[r][c]).enclose(array[r][c], builder);
            }
            builder.append(tableRow.END_TAG);
        }
        builder.append(table.END_TAG);
        return builder.toString();
    }
    
    public String toHtmlTable(Object[][] array, String[][] attributes) {
        int rowCount = array.length;
        int columnCount = array[0].length;

        StringBuilder builder = new StringBuilder(table.LENGTH
                + (tableRow.LENGTH + tableData.LENGTH * columnCount)
                * rowCount);

        builder.append(table.START_TAG);

        for (int r = 0; r < rowCount; r++) {
            builder.append(tableRow.START_TAG);
            for (int c = 0; c < columnCount; c++) {
                new HtmlTag("td", attributes[r][c]).enclose(array[r][c], builder);
            }
            builder.append(tableRow.END_TAG);
        }
        builder.append(table.END_TAG);
        return builder.toString();
    }
}
